<template>
    <div>
       <canvas ref="canvas"  @mousedown="startDrawing" @mousemove="draw" 
        @mouseup="stopDrawing"
       ></canvas>
       <div>
          <button @click="clearCanvas">清除</button>
          <button @click="saveSignature">保存</button>
          <button @click="downImg">下载</button>
       </div>
    </div>
</template>

<script>
export default {
  name: 'App',
  components: {
  },
  data(){
    return {
      context:'',//canvas 上下文
      isDrawing: false,//是否正在绘制
      DataUrl:''//签名图片的base64编码
    }
  },
  mounted(){
    this.context = this.$refs.canvas.getContext('2d');
    this.$refs.canvas.width = 500;
    this.$refs.canvas.height = 300;
  },
  methods:{
    //鼠标按下时触发
    startDrawing(event){
      this.isDrawing = true; 
      const {offsetX,offsetY} = event;
      console.log(event)
      // this.context.lineWidth = 5;
      this.context.beginPath();//开始绘制
      this.context.moveTo(offsetX,offsetY)
      
    },
    // 当鼠标在 Canvas 上移动时触发
    draw(event){
      if(!this.isDrawing)return;
      const {offsetX,offsetY} = event; 
      this.context.lineTo(offsetX,offsetY)
      this.context.strokeStyle="blue"
      this.context.stroke();
    },
    //当鼠标松开时触发，用于停止绘制签名
    stopDrawing(){
      this.isDrawing = false;
    },
    //清除画布
    clearCanvas(){
      const canvas = this.$refs.canvas;
      this.context.clearRect(0,0,this.$refs.canvas.width,this.$refs.canvas.height)
      this.DataUrl = ''
    },
    //保存签名
    saveSignature(){
      this.DataUrl =  this.$refs.canvas.toDataURL('image/png',1.0) //获取签名图片的base64编码
      
    },
    //封装下载图片方法
    downloadImg(url){
      const a = document.createElement('a');
      a.href = url
      a.download = '签名.png'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    },
    //下载图片
    downImg(){
      const canvas = this.$refs.canvas;
      console.log('this.isCanvasEmpty(canvas)',this.isCanvasBlank(canvas))
      if(this.isCanvasBlank(canvas)){
        alert('请先绘制签名！')
        return  
      }
      console.log('dataurl',this.DataUrl)
      if(!this.DataUrl){
        alert('请先保存图片！')
        return
      }
      this.downloadImg(this.DataUrl)
    },
    //验证canvas画布是否为空
    isCanvasBlank(canvas) {
        var blank = document.createElement('canvas');//系统获取一个空canvas对象
        blank.width = canvas.width;
        blank.height = canvas.height;
        return canvas.toDataURL() == blank.toDataURL();//比较值相等则为空
    }
    
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
canvas{
  border:1px solid red;
  background:bisque
}
</style>
